package com.leftheart.controller;


import com.leftheart.entity.User;
import com.leftheart.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("go")
public class LoginController {
//    @Autowired
//    UserService userService;

//    跳转至登录页面
    @RequestMapping("/tologin")
    public String toLogin(){
        return "index";
    }
//    登录
    @PostMapping("/login")
    public String login(String userName, String userPwd, Model model){
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(userName, userPwd);
        try {
            subject.login(token);
//            List<User> users = userService.queryAllUser();
//            model2.addAttribute("user",users);
            return "redirect:/books/toindex";
        }catch (UnknownAccountException e){
            model.addAttribute("msg","用户名错误");
            return "index";
        }catch (IncorrectCredentialsException e){
            model.addAttribute("msg","密码错误");
            return "index";
        }
    }

//    @RequestMapping("")
//    public ModelAndView forword1(){
//        ModelAndView modelAndView = new ModelAndView("/go/login");
//        modelAndView.addObject()
//    }
//    登出
    @RequestMapping("/loginOut")
    public String loginOut(HttpSession session, Model model){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        model.addAttribute("msg","退出成功");
        return "index";
    }
}
